﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Algobox.Structure.Finance.Strategies.FractionPrototype;
using System.ComponentModel;

namespace ZephyrLite
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            this.Show();

            Login loginForm = new Login();
            loginForm.Owner = this;
            loginForm.ShowDialog();

            if (!loginForm.DialogResult.HasValue || !loginForm.DialogResult.Value)
            {
                this.Close();
                return;
            }

            _zephyrLoader = new ZephyrLoader(loginForm.Username);

            _statusBar_ItemVersion.Content = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
            _statusBar_ItemVersion.Content += " " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();

            _dataGrid_FractionOpenMonitor.AutoGenerateColumns = false;
            _dataGrid_FractionOpenMonitor.ItemsSource = _zephyrLoader.FractionOpenView;
            _dataGrid_FractionDayMonitor.AutoGenerateColumns = false;
            _dataGrid_FractionDayMonitor.ItemsSource = _zephyrLoader.FractionDayMonitorView;
            _dataGrid_FractionOpenSettings.AutoGenerateColumns = false;
            _dataGrid_FractionOpenSettings.ItemsSource = _zephyrLoader.FractionOpenView;
            _dataGrid_FractionDaySettings.AutoGenerateColumns = false;
            _dataGrid_FractionDaySettings.ItemsSource = _zephyrLoader.FractionDayView;
            _dataGrid_FractionTriggers.AutoGenerateColumns = false;
            _dataGrid_FractionTriggers.ItemsSource = _zephyrLoader.FractionTriggerView;
        }

        ZephyrLoader _zephyrLoader;

        private void Connected(bool isEnabled)
        {
            if (isEnabled)
            {
                _zephyrLoader.TradingFeed.OnTradingFeedShutdown += new Action(OnFeedShutdown);
                _zephyrLoader.MarketFeed.OnMarketFeedShutdown += new Action(OnFeedShutdown);
                _button_FractionOpenSettingsAdd.IsEnabled = true;
                _button_FractionDaySettingsAdd.IsEnabled = true;
            }
        }


        void OnFeedShutdown()
        {
            if (_zephyrLoader.IsSterlingTraderToggleOn)
            {
                _statusBar_ConnectionSterling.Dispatcher.BeginInvoke(new UpdateStatusBarConnectionDelegate(UpdateStatusBarConnection), _statusBar_ConnectionSterling, new SolidColorBrush(Colors.Tomato));
            }
            else if (_zephyrLoader.IsSterlingSimulationToggleOn)
            {
                _statusBar_ConnectionSterling.Dispatcher.BeginInvoke(new UpdateStatusBarConnectionDelegate(UpdateStatusBarConnection), _statusBar_ConnectionSterling, new SolidColorBrush(Colors.Tomato));

            }
        }

        public delegate void UpdateStatusBarConnectionDelegate(params object[] args);

        void UpdateStatusBarConnection(params object[] args)
        {
            ((Control)args[0]).Background = (Brush)args[1];
        }


        private void ButtonConnectSterlingSimulation_Click(object sender, RoutedEventArgs e)
        {
            _menu_ConnectSterling.IsChecked = true;
            //_menu_ConnectBatsReplay.IsEnabled = false;
            _menu_ConnectSterling.IsEnabled = false;
            _menu_ConnectSterling.IsEnabled = false;

            System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();

            worker.DoWork += new System.ComponentModel.DoWorkEventHandler(ButtonConnectSterlingSimulation_Worker_DoWork);
            worker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(ButtonConnectSterlingSimulation_Worker_RunWorkerCompleted);
            worker.RunWorkerAsync();
        }
        private void ButtonConnectSterlingSimulation_Worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            e.Result = _zephyrLoader.Connect_SterlingSimulation();
        }
        private void ButtonConnectSterlingSimulation_Worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled || !(bool)e.Result)
            {
                _statusBar_ConnectionSterling.Background = new SolidColorBrush(Colors.Tomato);
            }
            else
            {
                _statusBar_ConnectionSterling.Background = new SolidColorBrush(Colors.YellowGreen);
                Connected(true);
            }
        }

        private void ButtonFractionOpenSettingsAdd_Click(object sender, RoutedEventArgs e)
        {
            _button_FractionOpenSettingsAdd.IsEnabled = false;

            BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();
            
            worker.DoWork += new DoWorkEventHandler(ButtonFractionOpenSettingsAdd_Worker_DoWork);
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(ButtonFractionOpenSettingsAdd_Worker_RunWorkerCompleted);

            if (!String.IsNullOrWhiteSpace(_textBox_FractionOpenSettings_StockA.Text)
                && !String.IsNullOrWhiteSpace(_textBox_FractionOpenSettings_StockB.Text))
            {
                var data = new Tuple<string, string>(_textBox_FractionOpenSettings_StockA.Text, _textBox_FractionOpenSettings_StockB.Text);

                worker.RunWorkerAsync(data);
            }

        }
        private void ButtonFractionOpenSettingsAdd_Worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            var data = e.Argument as Tuple<string, string>;

            _zephyrLoader.Fraction.AddOrUpdateOpen(Guid.NewGuid(), data.Item1, data.Item2);
        }
        private void ButtonFractionOpenSettingsAdd_Worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            _button_FractionOpenSettingsAdd.IsEnabled = true;
            _textBox_FractionOpenSettings_StockA.Clear();
            _textBox_FractionOpenSettings_StockB.Clear();
        }
        
        private void ButtonFractionDaySettingsAdd_Click(object sender, RoutedEventArgs e)
        {
            _button_FractionDaySettingsAdd.IsEnabled = false;

            BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();

            worker.DoWork += new DoWorkEventHandler(ButtonFractionDaySettingsAdd_Worker_DoWork);
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(ButtonFractionDaySettingsAdd_Worker_RunWorkerCompleted);
            
            if (!String.IsNullOrWhiteSpace(_textBox_FractionDaySettings_StockA.Text)
                && !String.IsNullOrWhiteSpace(_textBox_FractionDaySettings_StockB.Text))
            {
                var data = new Tuple<string, string>(_textBox_FractionDaySettings_StockA.Text, _textBox_FractionDaySettings_StockB.Text);

                worker.RunWorkerAsync(data);
            }
        }
        private void ButtonFractionDaySettingsAdd_Worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            var data = e.Argument as Tuple<string, string>;

            _zephyrLoader.Fraction.AddOrUpdateDay(Guid.NewGuid(), data.Item1, data.Item2);
        }
        private void ButtonFractionDaySettingsAdd_Worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            _button_FractionDaySettingsAdd.IsEnabled = true;
            _textBox_FractionDaySettings_StockA.Clear();
            _textBox_FractionDaySettings_StockB.Clear();
        }


        private void ButtonApplicationShutdown(object sender, RoutedEventArgs e)
        {
            if(_zephyrLoader != null)
                _zephyrLoader.Exit();
            Application.Current.Shutdown();
            this.Close();
        }

        private void ButtonSaveConfig(object sender, RoutedEventArgs e)
        {
            _zephyrLoader.SaveConfig();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void ButtonFractionOpen_Remove_Click(object sender, RoutedEventArgs e)
        {
            //Do whatever you wanted to do with MyObject.ID
            Algobox.Structure.Finance.Strategies.FractionPrototype.FractionComponentOpen strategy = ((FrameworkElement)sender).DataContext as Algobox.Structure.Finance.Strategies.FractionPrototype.FractionComponentOpen;
            if (strategy != null)
            {
                _zephyrLoader.FractionOpenRemove(strategy);
            }
        }

        private void ButtonFractionDay_Remove_Click(object sender, RoutedEventArgs e)
        {
            //Do whatever you wanted to do with MyObject.ID
            Algobox.Structure.Finance.Strategies.FractionPrototype.FractionComponentDay strategy = ((FrameworkElement)sender).DataContext as Algobox.Structure.Finance.Strategies.FractionPrototype.FractionComponentDay;
            if (strategy != null)
            {
                _zephyrLoader.FractionDayRemove(strategy);
            }
        }

        private void ButtonFractionTrigger_ExitA(object sender, RoutedEventArgs e)
        {
            Algobox.Structure.Finance.Strategies.FractionPrototype.FractionTrigger strategy = ((FrameworkElement)sender).DataContext as Algobox.Structure.Finance.Strategies.FractionPrototype.FractionTrigger;
            if (strategy != null)
            {
                strategy.ExitA();
            }
        }

        private void ButtonFractionTrigger_ExitB(object sender, RoutedEventArgs e)
        {
            Algobox.Structure.Finance.Strategies.FractionPrototype.FractionTrigger strategy = ((FrameworkElement)sender).DataContext as Algobox.Structure.Finance.Strategies.FractionPrototype.FractionTrigger;
            if (strategy != null)
            {
                strategy.ExitB();
            }
        }


        MenuItem _menu_BatsReplayLoadFile;

        private void ButtonConnectBatsReplay_Click(object sender, RoutedEventArgs e)
        {
            NLog.LogManager.GlobalThreshold = NLog.LogLevel.Error;
            NLog.LogManager.ReconfigExistingLoggers();

            _menu_ConnectBatsReplay.Click -= new RoutedEventHandler(ButtonConnectBatsReplay_Click);
            _menu_ConnectSterling.IsEnabled = false;

            System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();

            worker.DoWork += new System.ComponentModel.DoWorkEventHandler(ButtonConnectBatsReplay_Worker_DoWork);
            worker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(ButtonConnectBatsReplay_Worker_RunWorkerCompleted);
            worker.RunWorkerAsync();
        }
        private void ButtonConnectBatsReplay_Worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            e.Result = _zephyrLoader.Connect_BatsReplay();
        }
        private void ButtonConnectBatsReplay_Worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled || !(bool)e.Result)
            {
                _statusBar_ConnectionBatsReplay.Background = new SolidColorBrush(Colors.Tomato);
            }
            else
            {
                _menu_BatsReplayLoadFile = new MenuItem();
                _menu_BatsReplayLoadFile.Header = "Load File";
                _menu_BatsReplayLoadFile.Click += new RoutedEventHandler(ButtonBatsReplayLoadFile_Click);
                _menu_ConnectBatsReplay.Items.Add(_menu_BatsReplayLoadFile);

                _menu_BatsReplayLoadFile.IsEnabled = true;
                _statusBar_ConnectionBatsReplay.Background = new SolidColorBrush(Colors.YellowGreen);
                Connected(true);
            }
        }

        private void ButtonBatsReplayLoadFile_Click(object sender, RoutedEventArgs e)
        {
            _menu_ConnectBatsReplay.IsEnabled = false;

            System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();

            worker.DoWork += new System.ComponentModel.DoWorkEventHandler(ButtonBatsReplayLoadFile_Worker_DoWork);
            worker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(ButtonBatsReplayLoadFile_Worker_RunWorkerCompleted);
            worker.RunWorkerAsync();
        }
        private void ButtonBatsReplayLoadFile_Worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.DefaultExt = ".gz"; // Default file extension
            dlg.Filter = "GZip compressed files (.gz)|*.gz"; // Filter files by extension

            // Show open file dialog box
            Nullable<bool> result = dlg.ShowDialog();

            // Process open file dialog box results
            if (result == true)
            {
                _zephyrLoader.LoadFile_BatsReplay(dlg.FileName);
                e.Result = dlg.FileName;
                return;
            }

            e.Result = null;
        }
        private void ButtonBatsReplayLoadFile_Worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            if (!e.Cancelled && e.Error == null && e.Result is String)
            {
                MenuItem item = new MenuItem() { Header = (string)e.Result };
                item.Click += new RoutedEventHandler(ButtonBatsReplayLoadFileSpecific_Click);
                _menu_ConnectBatsReplay.Items.Add(item);
            }
            _menu_ConnectBatsReplay.IsEnabled = true;
        }
        
        private void ButtonBatsReplayLoadFileSpecific_Click(object sender, RoutedEventArgs e)
        {
            _menu_ConnectBatsReplay.IsEnabled = false;

            System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();

            worker.DoWork += new System.ComponentModel.DoWorkEventHandler(ButtonBatsReplayLoadFileSpecific_Worker_DoWork);
            worker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(ButtonBatsReplayLoadFileSpecific_Worker_RunWorkerCompleted);
            worker.RunWorkerAsync((string)((MenuItem)sender).Header);
        }
        private void ButtonBatsReplayLoadFileSpecific_Worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            if (e.Argument is String)
            {
                string filename = (string)e.Argument;
                _zephyrLoader.LoadFile_BatsReplay(filename);
            }
        }
        private void ButtonBatsReplayLoadFileSpecific_Worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            _menu_ConnectBatsReplay.IsEnabled = true;
        }

        private void ButtonApplicationShutdown(object sender, CancelEventArgs e)
        {
            if (_zephyrLoader != null)
                _zephyrLoader.Exit();
        }

    }
}
